package com.api.controller;

import com.api.mapper.NoticeMapper;
import com.api.mapper.UserMapper;
import com.api.pojo.Notice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/notice")
public class NoticeController {

    @Autowired
    NoticeMapper nm;

    @Autowired
    UserMapper um;

    @RequestMapping("/create")
    public Map<String, Object> create(Notice notice) {
        Map<String,Object> map = new HashMap<>();
        int code = 200;
        String msg = "ok";

        nm.create(notice);
        map.put("data", true);
        map.put("code", code);
        map.put("msg", msg);
        return map;
    }

    @RequestMapping("/remove")
    public Map<String, Object> remove(Integer id) {
        Map<String,Object> map = new HashMap<>();
        int code = 200;
        String msg = "ok";

        nm.remove(id);
        map.put("data", true);
        map.put("code", code);
        map.put("msg", msg);
        return map;
    }

    @RequestMapping("/update")
    public Map<String, Object> update(Notice notice) {
        Map<String,Object> map = new HashMap<>();
        int code = 200;
        String msg = "ok";

        nm.update(notice);
        map.put("data", true);
        map.put("code", code);
        map.put("msg", msg);
        return map;
    }

    @RequestMapping("/get")
    public Map<String, Object> get(Integer pageNo, Integer pageSize, String title) {
        Map<String,Object> map = new HashMap<>();
        int code = 200;
        String msg = "ok";

        pageNo = --pageNo * pageSize;
        List<Notice> list = title == null ? nm.get(pageNo, pageSize) : nm.getByTitle(pageNo, pageSize, "%" + title + "%");
        list.forEach(e -> {
            e.setUser(um.getById(e.getUid()));
        });

        map.put("data", list);
        map.put("total", title == null ? nm.count() : nm.countByTitle("%" + title + "%"));
        map.put("code", code);
        map.put("msg", msg);
        return map;
    }
}
